import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'News.dart';

class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._init();
  static Database? _database;

  DatabaseHelper._init();

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDB('news.db');
    return _database!;
  }

  Future<Database> _initDB(String fileName) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, fileName);
    return await openDatabase(path, version: 1, onCreate: _createDB);
  }

  Future _createDB(Database db, int version) async {
    await db.execute('''
    CREATE TABLE news (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      code INTEGER,
      msg TEXT,
      ctime TEXT,
      title TEXT,
      description TEXT,
      picUrl TEXT,
      url TEXT
    )
  ''');
    print('数据库表已创建');
  }

  Future<int> insertNews(News news) async {
    final db = await instance.database;
    return await db.insert('news', news.toMap());
  }

  Future<List<News>> getAllNews() async {
    final db = await instance.database;
    // 获取按 ID 降序排列的数据
    final result = await db.query('news', orderBy: 'id DESC');
    print('从本地数据库读取到 ${result.length} 条新闻数据');
    return result.map((json) => News.fromJson(json)).toList(); // 转换为 News 列表
  }

  Future close() async {
    final db = await instance.database;
    db.close();
  }
}

extension NewsExtensions on News {
  Map<String, dynamic> toMap() {
    return {
      'code': code,
      'msg': msg,
      'ctime': ctime,
      'title': title,
      'description': description,
      'picUrl': picUrl,
      'url': url,
    };
  }
}
